package com.ruoyi.backend2.filter;

import com.ruoyi.backend2.utils.GlobalThreadLocalUtil;
import com.ruoyi.backend2.utils.jwt.JWTUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class LoginFilter implements Filter {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (request.getRequestURI().contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("token不存在！");
        }
        Claims claims = JWTUtils.parseToken(token);
        int id = (int) claims.get("id");
        if (!redisTemplate.hasKey("user:" + id)) {
            throw new RuntimeException("token已经过期！");
        }
        GlobalThreadLocalUtil.set("id", id);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
